package com.lyq.leetcode.最大子数组和53;

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        System.out.println(main.maxSubArray1(new int[]{-2,1,-3,4,-1,2,1,-5,4}));
    }

    /**
     * 利用滑动窗口，找出每个窗口的最大值
     *
     * @param nums 输入
     * @return 最大子数组值
     */
    public int maxSubArray(int[] nums) {
        int res = Integer.MIN_VALUE;
        int temp = -10001;
        for (int num : nums) {
            if (temp + num <= num) {
                temp = num;
            } else {
                temp += num;
            }
            res = Math.max(res, temp);
        }
        return res;
    }

    /**
     * 利用动态规划查找每一组的最大值
     *
     * @param nums 输入
     * @return 最大子数组值
     */
    public int maxSubArray1(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int res=Integer.MIN_VALUE;
        for (int i = 1; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
            res=Math.max(res,dp[i]);
        }
        return res;
    }
}
